<template>
  <view class="openQuota">
    <view class="notice">
      <view class="notice-box">
        <image
          src="@/static/team/shopkeeper/notice.png"
          mode="widthFix"
        ></image>
        <view class="notice-text">名额赠送兑换后不可撤回，请谨慎操作</view>
      </view>
    </view>

    <view class="foodr-list">
      <view class="list-index">
        <view class="list-index-left">选择兑换券</view>
        <view class="list-index-right" v-if="type == 1">
          {{ type == 1 && det.level ? det.level.name + "身份兑换券" : "" }}
          <!-- <u-icon name="arrow-right" color="#8C8C8C" size="16"></u-icon> -->
        </view>
        <view class="list-index-right" v-if="type == 2">
          {{ type == 2 && det.grade ? det.grade.name + "身份兑换券" : "" }}
          <!-- <u-icon name="arrow-right" color="#8C8C8C" size="16"></u-icon> -->
        </view>
      </view>
      <view class="list-index" v-if="type == 2">
        <view class="list-index-left">选择代理等级</view>

        <view class="list-index-right" @click="selectqdfun">
          {{ dltext ? dltext : "代理级别" }}
          <u-icon name="arrow-right" color="#8C8C8C" size="16"></u-icon>
        </view>
      </view>
      <view class="list-index" v-if="type == 2 && dltext">
        <view class="list-index-left">选择代理区域</view>

        <view class="list-index-right" @click="showaddressfun">
          <text v-if="fromdate.operating_area.province">
            {{ selecttow == 0 ? fromdate.operating_area.province : "" }}
            {{
              selecttow == 1
                ? fromdate.operating_area.province +
                  "/" +
                  fromdate.operating_area.city
                : ""
            }}
            {{
              selecttow == 2
                ? fromdate.operating_area.province +
                  "/" +
                  fromdate.operating_area.city +
                  "/" +
                  fromdate.operating_area.area
                : ""
            }}
          </text>
          <text
            v-if="fromdate.operating_area && !fromdate.operating_area.province"
            >{{
              selecttow == 0
                ? "请选择省"
                : selecttow == 1
                ? "请选择省/市"
                : selecttow == 2
                ? "请选择省/市/区"
                : ""
            }}</text
          >
          <u-icon name="arrow-right" color="#8C8C8C" size="16"></u-icon>
        </view>
      </view>

      <view class="list-index">
        <view class="list-index-left">手机号查找对象</view>
      </view>
      <view class="list-footer">
        <view class="list-index-input">
          <up-input
            placeholder="输入对方手机号，开通身份"
            border="none"
            clearable
            v-model="phone"
          >
          </up-input>
          <view
            :class="phone.length == 11 ? 'selectuseracitve' : 'selectuser'"
            @click="selectuser"
            >查询</view
          >
        </view>
      </view>
    </view>

    <view class="footer-card" v-if="userobj.uid && phone.length == 11">
      <view class="user-card-img">
        <!-- {{ arrurl }} -->
        <image
          :src="userobj.avatar ? userobj.avatar : arrurl"
          mode="widthFix"
        ></image>
      </view>
      <view class="user-card-identity">{{ userobj.level_name }}</view>
      <view class="user-card-name">{{ userobj.nickname }}</view>

      <view class="user-card-info">
        <view class="info-id">ID：{{ userobj.uid }} </view>
        <view class="info-phone">手机号：{{ userobj.phone }}</view>
      </view>
      <view class="footer-btn" @click="ktfun">为他开通</view>
    </view>

    <view class="footer-text"
      >兑换券开通的身份，不含“赠品奖励”，不计算直推升级奖励。
      该身份有效期为5年，以赠送成功之日起算。</view
    >
  </view>

  <!-- 赠送商品弹框 -->
  <view class="password_show">
    <u-popup
      :show="showPopup"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="productGift">
        <view class="popup-content-title">温馨提示</view>
        <view class="popup-content-item"
          >开通后无法撤回，请确认为<text
            >“{{ userobj.nickname }}-{{ userobj.phone }}”</text
          >开通？</view
        >
        <view class="popup-content-box">
          <view class="popup-content-bt">
            <view class="popup-content-qx" @click="showPopup = false"
              >取消</view
            >
            <view class="popup-content-cl" @click="gopassword">确定赠送</view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>

  <up-picker
    :show="addresshow"
    ref="uPickerRef"
    :columns="columns"
    keyName="name"
    @cancel="canceladdress"
    @confirm="confirmaddress"
    @change="changeHandler"
  ></up-picker>
  <up-picker
    :show="showtwo"
    :columns="columnstwo"
    @cancel="canceladdress"
    @confirm="confirmdl"
  ></up-picker>

  <!-- 密码弹框 -->
  <view class="password_show">
    <u-popup
      :show="showPassword"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="password">
        <view class="popup-content-title">支付密码</view>
        <u-code-input
          v-model="pay_pass"
          :maxlength="6"
          dot
          size="80"
          @change="onChange"
          @finish="finish"
          :focus="focusinput"
        ></u-code-input>
        <view class="footer">
          <view class="closefun" @click="showPassword = false">取消</view>
          <view class="forgot" @click="forgot">忘记密码？</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { inject, ref } from "vue";
import arrurl from "@/static/team/shopkeeper/user-img.png";
import { areaListApi } from "@/services/address";

import {
  rolledlist,
  rolledetail,
  upgradeUserQuery,
  useUpgrade,
  agencyUserQuery,
  useAgency,
} from "@/services/team";
import { onShow } from "@dcloudio/uni-app";
import { mine, isPayPassApi, checkPayPass } from "@/services/user";

const props = defineProps({
  product_type: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
});

onShow(() => {
  isPayPassFun();
});

const panme = ref({
  page: 1,
  limit: 1000,
  product_type: 1,
});
const det = ref({});
const type = ref(1);
if (props.product_type) {
  type.value = props.product_typ;
}
type.value = props.product_type;
const list = ref([]);
const phone = ref("");
const userobj = ref({});

const showPopup = ref(false);
// getlist();
async function getlist() {
  let res = await rolledlist(panme.value);
  if (res.code == 200) {
    list.value = res.data.list;
  }
}
upgradeagreeInfofun();
async function upgradeagreeInfofun() {
  let res = await rolledetail({ id: props.id });
  if (res.code == 200) {
    det.value = res.data;
  }
}

const selectuser = async () => {
  userobj.value = {};
  if (phone.value.length != 11) {
    uni.showToast({
      title: "手机号码格式不正确!",
      icon: "none",
    });
    return;
  }
  try {
    if (type.value == 1) {
      let res = await upgradeUserQuery({
        verify_code: det.value.verify_code,
        phone: phone.value,
      });
      if (res.code == 200) {
        userobj.value = res.data;
      }
    } else {
      let res = await agencyUserQuery({
        verify_code: det.value.verify_code,
        phone: phone.value,
      });
      if (res.code == 200) {
        userobj.value = res.data;
      }
    }
  } catch (e) {
    if (e.info == "用户不存在") {
      uni.showToast({
        title: "您不是他的推荐人，无法查询",
        icon: "none",
      });
    } else {
      uni.$u.toast(e.info);
    }
    // uni.$u.toast(e.info);
    userobj.value = {};
  }
};

const close = () => {
  showPopup.value = false;
  showPassword.value = false;
  focusinput.value = false;
  pay_pass.value = "";
};

const isPayPass = ref(0);
const isPayPassFun = async () => {
  try {
    let res = await isPayPassApi();
    if (res.code == 200) {
      isPayPass.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const showPassword = ref(false);
const gopassword = () => {
  if (isPayPass.value != 0) {
    showPassword.value = true;
    pay_pass.value = "";
    setTimeout(() => {
      focusinput.value = true;
    }, 500);
  } else {
    uni.showToast({
      title: "没有支付密码，前往设置",
      icon: "none",
    });
    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
      });
    }, 500);
  }
};

const pay_pass = ref("");
const gocancle = () => {
  showPassword.value = false;
  pay_pass.value = "";
};
const ispay = ref(false);
const popupSubmit = async () => {
  // uni.redirectTo({
  //   url: "/pages/team/paystate/index",
  // });

  // return;
  try {
    if (type.value == 1) {
      // 防止小程序输入密码重复支付
      if (!ispay.value) {
        ispay.value = true;
      } else {
        return;
      }
      let res = await useUpgrade({
        uid: userobj.value.uid,
        verify_code: det.value.verify_code,
        pay_pass: pay_pass.value,
      });
      if (res.code == 200) {
        uni.$u.toast("使用成功");
        setTimeout(() => {
          uni.redirectTo({
            url: "/pages/team/paystate/index",
          });
          showPopup.value = false;
          pay_pass.value = "";
          focusinput.value = false;
        });
      }
    } else {
      if (!fromdate.value.operating_area.region) {
        uni.$u.toast("请选择地区");
        return;
      }

      let res = await useAgency({
        uid: userobj.value.uid,
        verify_code: det.value.verify_code,
        region: fromdate.value.operating_area.region,
      });
      if (res.code == 200) {
        uni.$u.toast("使用成功");
        setTimeout(() => {
          uni.redirectTo({
            url: "/pages/team/paystate/index",
          });
          showPopup.value = false;
          pay_pass.value = "";
          focusinput.value = false;
        });
      }
    }
  } catch (e) {
    uni.$u.toast(e.info);
    pay_pass.value = "";
  }
};

const ktfun = async () => {
  showPopup.value = true;
};

// 地区
const columnstwo = ref([["省代", "市代", "区代"]]);
const showtwo = ref(false);
const dltext = ref("");
const selecttow = ref("");

const addresshow = ref(false);
const columns = ref([]);

const province = ref([]);
const city = ref([]);
const county = ref([]);
const addressdata = ref([]);
const fromdate = ref({ operating_area: {} });

// 获取地区数据
async function areaListFun() {
  //发送请求
  let res = await areaListApi();
  columns.value;
  addressdata.value = res.data;
  province.value = res.data;
  city.value = res.data[0].sub;
  county.value = res.data[0].sub[0].sub;
  columns.value.push(province.value, city.value, county.value);
}

const showaddressfun = () => {
  columns.value = [];

  if (selecttow.value == 0) {
    columns.value.push(province.value);
  }
  if (selecttow.value == 1) {
    columns.value.push(province.value, city.value);
  }
  if (selecttow.value == 2) {
    columns.value.push(province.value, city.value, county.value);
  }
  addresshow.value = true;
};
const confirmaddress = (e) => {
  if (selecttow.value == 0) {
    fromdate.value.operating_area = {
      province: e.value[0].name,
      region: e.value[0].code,
    };
  }
  if (selecttow.value == 1) {
    fromdate.value.operating_area = {
      province: e.value[0].name,
      city: e.value[1].name,
      region: e.value[1].code,
    };
  }
  if (selecttow.value == 2) {
    fromdate.value.operating_area = {
      province: e.value[0].name,
      city: e.value[1].name,
      area: e.value[2].name,
      region: e.value[2].code,
    };
  }
  // fromdate.value

  addresshow.value = false;
};
const selectqdfun = () => {
  if (addressdata.value.length <= 0) {
    areaListFun();
  }

  showtwo.value = true;
};
const confirmdl = (e) => {
  selecttow.value = e.indexs[0];
  dltext.value = e.value[0];
  fromdate.value.operating_area = {};
  showtwo.value = false;
};
const canceladdress = () => {
  addresshow.value = false;
  showtwo.value = false;
};
const changeHandler = (e) => {
  const { columnIndex, value, values, index, indexs, code } = e;

  city.value = [];
  county.value = [];
  let lenghts = addressdata.value[indexs[0]].sub.length;
  if (
    addressdata.value &&
    addressdata.value[indexs[0]].sub &&
    !addressdata.value[indexs[0]].sub[indexs[1]]
  ) {
    city.value =
      addressdata.value &&
      addressdata.value[indexs[0]] &&
      addressdata.value[indexs[0]].sub;
    county.value =
      addressdata.value &&
      addressdata.value[indexs[0]] &&
      addressdata.value[indexs[0]].sub[lenghts - 1] &&
      addressdata.value[indexs[0]].sub[lenghts - 1].sub;
  } else {
    city.value =
      addressdata.value &&
      addressdata.value[indexs[0]] &&
      addressdata.value[indexs[0]].sub;
    county.value =
      addressdata.value &&
      addressdata.value[indexs[0]] &&
      addressdata.value[indexs[0]].sub[indexs[1]] &&
      addressdata.value[indexs[0]].sub[indexs[1]].sub;
  }
  columns.value = [];
  if (selecttow.value == 0) {
    columns.value.push(province.value);
  }
  if (selecttow.value == 1) {
    columns.value.push(province.value, city.value);
  }
  if (selecttow.value == 2) {
    columns.value.push(province.value, city.value, county.value);
  }
  // columns.value.push(province.value, city.value, county.value);
};

// 定义 finish 方法
const finish = async (e) => {
  pay_pass.value = e;
  try {
    let res = await checkPayPass({ pay_pass: pay_pass.value });
    if (res.code == 200) {
      popupSubmit();
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
  }
};

const forgot = () => {
  uni.navigateTo({
    url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
  });
};

const focusinput = ref(false);
</script>

<style lang="scss" scoped>
@import "./openQuota.scss";
</style>
